package com.sn.author.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.sn.author.common.enums.*;
import com.sn.author.common.exception.BadRequestException;
import com.sn.author.dao.ImportAccountMapper;
import com.sn.author.dao.TaskMapper;
import com.sn.author.domain.BaseResult;
import com.sn.author.domain.dto.AccountDTO;
import com.sn.author.domain.dto.TaskBasisInfo;
import com.sn.author.domain.entity.ImportAccount;
import com.sn.author.domain.entity.Task;
import com.sn.author.domain.taskEntity.TaskProcess;
import com.sn.author.domain.vo.*;
import com.sn.author.filter.content.SecurityContextHolder;
import com.sn.author.service.dao.AccountService;
import com.sn.author.service.dao.PushMessageService;
import com.sn.author.service.dao.TaskService;
import com.sn.author.utils.*;
import com.sn.author.utils.export.AccountExport;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.json.JSONParserTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private ImportAccountMapper importAccountMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private SdkProcessService sdkProcessService;

    @Autowired
    private PushMessageService pushMessageService;



    @Override
    public BaseResult<List<AccountDTO>> getAccountList(QueryAccountVo queryAccountVo) {
        startPage(queryAccountVo);
        List<ImportAccount> list = importAccountMapper.selectSort("import_time DESC");
        PageInfo<ImportAccount> pageInfo = new PageInfo<>(list);
        return BaseResult.success(BeanUtils.coventObject(pageInfo.getList(),AccountDTO.class),pageInfo.getTotal());
    }

    @Override
    public Boolean delAccount(Long id) {
        try {
            importAccountMapper.deleteByPrimaryKey(id);
        }catch (Exception e){
            throw new BadRequestException("删除失败 错误信息:" + e.getMessage());
        }
        return true;
    }

    @Override
    public void exportAccount() {
        List<ImportAccount> data = importAccountMapper.selectAll();
        Assert.isTrue(!data.isEmpty(),"无数据可导出");
        String[] title = {"序号","手机号码","点赞","评论","关注","ip","最后一次登录时间"};
        Export export = new AccountExport(Arrays.asList(title),"账号文件_" + DateUtils.formatDate(new Date(),DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS));
        export.generateWorkBookTitle().writeData(data).download();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskBasisInfo loginDy(List<LoginVo> accounts) {
        //生成任务基本信息
        Task task = buildTaskBasisInfo(accounts);
        taskMapper.insert(task);
        //构建任务模型
        taskService.generateJobToPool(TaskServiceImpl.buildLoginTaskModelList(accounts,task.getId()),task.getId());
        //推送开始消息
        pushMessageService.pushMessage(PushMessageService.buildTaskPushMessage(TaskService.getTaskMsg(TaskTypeEnum.LOGIN.getType()),"-1",TaskTypeEnum.LOGIN.getType()));
        return new TaskBasisInfo(task.getId(),task.getTaskType());
    }

    private Task buildTaskBasisInfo(List<LoginVo> accounts) {
        Task task = new Task();
        task.setTaskType(TaskTypeEnum.LOGIN.getType());
        task.setStatus(TaskEnums.AWAIT.getCode());
        task.setTaskId(Utils.getGuid());
        task.setUserId(SecurityContextHolder.getCurrentUserId());
        task.setStartTime(DateUtils.formatYMDHMS(new Date()));
        task.setTaskConfig(JSON.toJSONString(accounts));
        return task;
    }

    @Override
    public Boolean batchRegister(Integer num) {
        sdkProcessService.executeRegisterSdk(num);
        return true;
    }

    @Override
    public Boolean batchLogin(BatchLoginVo batchLoginVo) {
        List<ImportAccount> accounts;
        if(batchLoginVo.getUserIds().size() == 1 && batchLoginVo.getUserIds().get(0).equals("-1")){
            accounts = importAccountMapper.selectAll();
        }else{
            accounts = importAccountMapper.selectByIds(batchLoginVo.getUserIds());
        }
        List<LoginVo> loginVos = accounts.stream().map(a -> {
            LoginVo vo = new LoginVo();
            vo.setPassword(a.getPassword());
            vo.setUserName(a.getPhone());
            return vo;
        }).collect(Collectors.toList());
        loginDy(loginVos);
        return true;
    }

    @Override
    public void updateAttentionCount(String phone, int i) {
        importAccountMapper.addAttentionCount(phone,i);
    }

    @Override
    public void updateLikeCount(String phone, int i) {
        importAccountMapper.addLikeCount(phone,i);
    }

    @Override
    public void updateCommentCount(String phone, int i) {
        importAccountMapper.addCommentCount(phone,i);
    }

    @Override
    public ImportAccount getOnlineAccount() {
        return importAccountMapper.selectOnlineAccount();
    }
}
